package com.faithbj.device.web.controller.admin;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.faithbj.device.model.entity.Consumable;
import com.faithbj.device.model.entity.Stock;
import com.faithbj.device.model.entity.StockItem;
import com.faithbj.device.service.ConsumableService;
import com.faithbj.device.service.StockItemService;
import com.faithbj.device.service.StockService;
import com.faithbj.device.utils.DateUtils;
import com.faithbj.device.model.configuration.AcessoryAtrributeAndParameter;

@Controller
@RequestMapping("/faith/stock")
public class AdminStockController extends BaseAdminController {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4784506615400387088L;
	
/*   @Override
    public void initBinder(WebDataBinder binder) {  
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
        dateFormat.setLenient(false);  
        binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, false));  
    }  */
	
	
	private final String OPERRATE_RETURN_URL="list/";
	private final String INLIST="admin/instock_info_list";
	private final String ININPUT="admin/instock_info_input";
	
	private final String OUTLIST="admin/outstock_info_list";
	private final String OUTINPUT="admin/outstock_info_input";
	
	@Resource
	private StockService stockService;
	
	@Resource
	private StockItemService stockItemService;
	@Resource
	private ConsumableService consuambleService;
	
	// 列表
		@RequestMapping("list/{isInStock}")
		public String list(ModelMap map,@PathVariable int isInStock) {
			pager = stockService.findByPager(pager,isInStock);
			map.put("pager", pager);
			if(isInStock==1){
				return INLIST;
			}
			return OUTLIST;
		}
		
		
		

		// 添加
		@RequestMapping("new/{isInStock}")
		public String add(ModelMap map,@PathVariable int isInStock) {
			map.put("isAddAction", true);
			map.put("isInStock", isInStock);
			if(isInStock==1){
				return ININPUT;
			}
			return OUTINPUT;
		}
		
		// 编辑
		@RequestMapping("edit/{id}/{isInStock}")
		public String edit(@PathVariable String id,ModelMap map,@PathVariable int isInStock) {
			Stock con = stockService.load(id);
			map.put("stock", con);
			map.put("isInStock", isInStock);
			map.put("isAddAction", false);
			if(isInStock==1){
				return ININPUT;
			}
			return OUTINPUT;
		}
		
		// 删除
		@RequestMapping("delete/{id}/{isInStock}")
		public String delete(@PathVariable String id,ModelMap map,@PathVariable String isInStock){
			Stock stock = stockService.load(id);
			Iterator iterator = stock.getStockDetailSet().iterator();
			while (iterator.hasNext()){
				StockItem st = (StockItem)iterator.next();
				Consumable con = consuambleService.findByCode(st.getConsumable().getSn());
				if(isInStock.equals("1")){
					con.setCount(con.getCount()-st.getCount());
					con.setInCount(con.getInCount()-st.getCount());
				}else if(isInStock.equals("0")){
					con.setCount(con.getCount()+st.getCount());
					con.setOutCount(con.getOutCount()-st.getCount());
					stock.setPrice(stock.getPrice().subtract(st.getPrice()));
				}else{
					map.put("errorMessages", "出入库类型不明确");
					return ERROR;
				}
				consuambleService.update(con);
			}
			stockService.delete(id);
			map.put("redirectUrl", "../../"+OPERRATE_RETURN_URL+isInStock);
			return SUCCESS;
		}

		// 保存
		@SuppressWarnings("unchecked")
		@RequestMapping(value="save/{isInStock}",method = RequestMethod.POST)
		public String save(Stock stock,@RequestParam String sdate,AcessoryAtrributeAndParameter acessoryAtrributes, ModelMap map,@PathVariable String isInStock) {
 			stock.setDate(DateUtils.getStringToDate(sdate, "yyyy-MM-dd"));
			BigDecimal price =  new BigDecimal(0) ;
			Set<StockItem> stockItemSet = new HashSet<StockItem>();
			if(acessoryAtrributes.getProductAttributeList()!=null){
				stockItemSet=new HashSet<StockItem>(acessoryAtrributes.getProductAttributeList());
				for(StockItem st : acessoryAtrributes.getProductAttributeList()){
					Consumable con = consuambleService.findByCode(st.getConsumable().getSn());
					if(con==null){
						map.put("errorMessages", "添加失败");
						map.put("redirectUrl", "../"+OPERRATE_RETURN_URL+isInStock);
						return ERROR;
					}
					if(isInStock.equals("1")){
						con.setInCount(st.getCount()+con.getInCount());
						con.setCount(con.getCount()+st.getCount());
					}
					if(isInStock.equals("0")){
						con.setOutCount(st.getCount()+con.getOutCount());
						con.setCount(con.getCount()-st.getCount());
					}
					consuambleService.update(con);
					st.setConsumable(con);
					st.setPrice(con.getPrice().multiply(new BigDecimal(st.getCount())));
					price=con.getPrice().multiply(new BigDecimal(st.getCount())).add(price);
					st.setStock(stock);
					stockItemSet.add(st);
				}
			}
			stock.setStockDetailSet(stockItemSet);
			
			stock.setIsInStock(Integer.parseInt(isInStock));
			stock.setPrice(price);
			stockService.save(stock);
			
			map.put("redirectUrl", "../"+OPERRATE_RETURN_URL+isInStock);
			return SUCCESS;
		}

		// 更新
		@RequestMapping(value="update/{isInStock}",method = RequestMethod.POST)
		public String update(Stock stock,@RequestParam String sdate,AcessoryAtrributeAndParameter acessoryAtrributes, ModelMap map,@PathVariable String isInStock) {
			Stock persistent = stockService.get(stock.getId());
//			BeanUtils.copyProperties(stock, persistent, new String[] {"id", "createDate", "modifyDate"});
			Set<StockItem> stockItemSet = new HashSet<StockItem>();
			BigDecimal price =  new BigDecimal(0) ;
			if(acessoryAtrributes.getProductAttributeList()!=null){
				stockItemSet=new HashSet<StockItem>(acessoryAtrributes.getProductAttributeList());
				for(StockItem st : acessoryAtrributes.getProductAttributeList()){
					Consumable con = consuambleService.findByCode(st.getConsumable().getSn());
					
					if(st.getId()!=null){
						//如果id不为空，比条信息为修改，
						Iterator iterator = persistent.getStockDetailSet().iterator();
						while(iterator.hasNext()){
							StockItem stockItem = (StockItem)iterator.next();
							if(st.getId().equals(stockItem.getId())){
								if(isInStock.equals("1")){
									//，先将原来的数量减去
									con.setInCount(con.getInCount()-stockItem.getCount());
									con.setCount(con.getCount()-stockItem.getCount());
									//再加上现在的数量
									con.setInCount(st.getCount()+con.getInCount());
									con.setCount(con.getCount()+st.getCount());
								}
								if(isInStock.equals("0")){
									//，先将原来的数量减去
									con.setOutCount(con.getOutCount()-stockItem.getCount());
									con.setCount(con.getCount()-stockItem.getCount());
									
									//再加上现在的数量
									con.setInCount(st.getCount()+con.getInCount());
									con.setCount(con.getCount()+st.getCount());
								}
								break;
							}
						}
						
					}
					else{
						//如果id不为空，比条信息为增加物品项的信息，加上现在的数量
						if(isInStock.equals("1")){
							con.setInCount(st.getCount()+con.getInCount());
							con.setCount(con.getCount()+st.getCount());
						}
						if(isInStock.equals("0")){
							con.setOutCount(st.getCount()+con.getOutCount());
							con.setCount(con.getCount()-st.getCount());
						}
					}
					consuambleService.update(con);
					st.setConsumable(con);
					st.setPrice(con.getPrice().multiply(new BigDecimal(st.getCount())));
					st.setStock(stock);
					price=con.getPrice().multiply(new BigDecimal(st.getCount())).add(price);
					stockItemSet.add(st);
				}
			}
			persistent.setStockDetailSet(stockItemSet);
			persistent.setCode(stock.getCode());
			persistent.setComments(stock.getComments());
			persistent.setDescription(stock.getDescription());
			persistent.setStockor(stock.getStockor());
			persistent.setIsInStock(Integer.parseInt(isInStock));
			persistent.setPrice(price);
			
			persistent.setDate(DateUtils.getStringToDate(sdate, "yyyy-MM-dd"));
			stockService.update(persistent);

			map.put("redirectUrl", "../"+OPERRATE_RETURN_URL+isInStock);
			return SUCCESS;
		}

}
